package com.example.blog.utils;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtParser;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.io.Decoders;
import io.jsonwebtoken.io.Encoders;
import io.jsonwebtoken.security.Keys;
import org.junit.jupiter.api.Test;

import javax.crypto.SecretKey;
import java.security.Key;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class JWTUtils {
    private long expiration  = 30*60*1000;
    private static String setSigningKey = "tkxN7pOT3U8GpuwhiHu3QDSFBVGQD9oHWmeF8xtYeeU=";
    private static Key key = Keys.hmacShaKeyFor(Decoders.BASE64.decode(setSigningKey));
    @Test
    public void genJWT(){
        //生成签名需要的对象(现在里面换成了方法自动生成的安全签名)
        Map<String,Object> data = new HashMap<>();
        data.put("id",2);
        data.put("name","zhangsan");

        //String compact = Jwts.builder().setClaims(data).compact();//生成令牌(这个没有生成签名)
        String compact = Jwts.builder()
                .setClaims(data)
                .setExpiration(new Date(System.currentTimeMillis()+expiration))
                .signWith(key)
                .compact();//有签名版
        System.out.println(compact);
    }

    //生成一个key,因为太简单就会报错
    @Test
    void genKey(){
        SecretKey secretKey = Keys.secretKeyFor(SignatureAlgorithm.HS256);
        String encode = Encoders.BASE64.encode(secretKey.getEncoded());
        System.out.println(encode);
    }

    //校验
    @Test
    void verify(){
        String token = "eyJhbGciOiJIUzI1NiJ9.eyJuYW1lIjoiemhhbmdzYW4iLCJpZCI6Mn0.nRSk-gubomJzXB5H8qY6YV1H2GLcPTyQqW39mxsMRqY";//这是生成的令牌
        JwtParser build = Jwts.parserBuilder().setSigningKey(key).build();
        Claims body = build.parseClaimsJws(token).getBody();
        System.out.println(body.get("id"));
        System.out.println(body.get("name"));
    }
}
